// my-fresh-blog/routes/posts/edit.tsx
import { Handlers, PageProps, FreshContext } from "$fresh/server.ts";
import { getDbClient, Post } from "../../utils/db.ts";
import HeadComponent from "../../components/Head.tsx";

interface EditPostPageData { post: Post | null; error?: string; idFromQuery?: string; }
export const handler: Handlers<EditPostPageData> = {
  async GET(req, ctx: FreshContext) {
    if (!ctx.state.isAdmin) {
      const headers = new Headers(); const encodedRedirect = encodeURIComponent(new URL(req.url).href);
      headers.set("location", `/admin/login?redirect=${encodedRedirect}`);
      return new Response(null, { status: 303, headers });
    }
    const url = new URL(req.url); const id = url.searchParams.get("id");
    if (!id) return ctx.render({ post: null, error: "需要提供文章 ID 进行编辑。", idFromQuery: undefined });
    let client;
    try {
      client = await getDbClient();
      const results = await client.query("SELECT id, title, content FROM posts WHERE id = ?", [id]);
      const post = results && results.length > 0 ? results[0] as Post : null;
      if (!post) return ctx.render({ post: null, error: `ID 为 ${id} 的文章未找到。`, idFromQuery: id });
      return ctx.render({ post, idFromQuery: id });
    } catch (error) { console.error(`Error fetching post ID ${id} for edit:`, error); return ctx.render({ post: null, error: "获取文章数据失败。", idFromQuery: id });
    } finally { if (client) await client.close(); }
  },
  async POST(req, ctx: FreshContext) {
    if (!ctx.state.isAdmin) return new Response("Unauthorized", { status: 403 });
    const url = new URL(req.url); const id = url.searchParams.get("id");
    const form = await req.formData();
    const title = (form.get("title") as string || "").trim();
    const content = (form.get("content") as string || "").trim();
    if (!id) return new Response("Post ID missing", { status: 400 });
    if (!title || !content) {
      const headers = new Headers(); const errorMsg = encodeURIComponent("标题和内容不能为空。");
      headers.set("location", `/posts/edit?id=${id}&error=${errorMsg}`);
      return new Response(null, { status: 303, headers });
    }
    let client;
    try {
      client = await getDbClient();
      const result = await client.execute("UPDATE posts SET title = ?, content = ? WHERE id = ?", [title, content, id]);
      if (result.affectedRows === 0) {
         const headers = new Headers(); const errorMsg = encodeURIComponent(`更新失败：ID 为 ${id} 的文章未找到。`);
         headers.set("location", `/posts/edit?id=${id}&error=${errorMsg}`);
         return new Response(null, { status: 303, headers });
      }
    } catch (error) {
      console.error(`Error updating post ID ${id}:`, error);
      const headers = new Headers(); const errorMsg = encodeURIComponent(`更新文章失败: ${error.message || "未知错误"}`);
      headers.set("location", `/posts/edit?id=${id}&error=${errorMsg}`);
      return new Response(null, { status: 303, headers });
    } finally { if (client) await client.close(); }
    const headers = new Headers(); headers.set("location", `/posts/${id}?updated=true`);
    return new Response(null, { status: 303, headers });
  },
};

export default function EditPostPage({ data, url }: PageProps<EditPostPageData>) {
  const { post, error: initialError, idFromQuery } = data;
  const formErrorFromRedirect = url.searchParams.get("error");
  const displayError = formErrorFromRedirect || initialError;
  const currentPostId = post?.id?.toString() || idFromQuery;

  if (displayError && !post) {
     return ( <> <HeadComponent title="编辑错误" /> <div class="max-w-screen-md mx-auto bg-brand-card-bg backdrop-blur-md p-6 sm:p-8 rounded-xl shadow-2xl border border-slate-700 my-8 text-center"> <h1 class="text-2xl font-bold text-red-400 mb-4">操作失败</h1> <p class="text-red-300 mb-6">{decodeURIComponent(displayError)}</p> {currentPostId ? (<a href={`/posts/${currentPostId}`} class="text-purple-400 hover:text-pink-400 hover:underline">返回文章</a>) : (<a href={`/`} class="text-purple-400 hover:text-pink-400 hover:underline">返回首页</a>)} </div> </> );
  }
  if (!post) { return <p class="text-center text-slate-400 py-10">加载中或文章不存在...</p>; }

  return (
    <>
      <HeadComponent title={`编辑: ${post.title}`} />
      <div class="max-w-screen-md mx-auto bg-brand-card-bg backdrop-blur-md p-6 sm:p-8 rounded-xl shadow-2xl border border-slate-700 my-8">
        <h1 class="text-3xl font-bold mb-8 text-slate-100">编辑文章</h1>
        {displayError && (
            <div class="bg-red-500 bg-opacity-30 border-l-4 border-red-500 text-red-200 p-4 mb-6 rounded-md" role="alert">
                <p class="font-bold">提示:</p><p>{decodeURIComponent(displayError)}</p>
            </div>
        )}
        <form method="POST" action={`/posts/edit?id=${post.id}`} class="space-y-6">
          <div>
            <label htmlFor="title" class="block text-sm font-medium text-slate-300 mb-1">标题</label>
            <input type="text" name="title" id="title" required defaultValue={post.title} class="mt-1 block w-full px-4 py-3 border border-slate-600 bg-slate-800 text-slate-200 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500 sm:text-sm" />
          </div>
          <div>
            <label htmlFor="content" class="block text-sm font-medium text-slate-300 mb-1">内容</label>
            <textarea name="content" id="content" rows={15} required defaultValue={post.content} class="mt-1 block w-full px-4 py-3 border border-slate-600 bg-slate-800 text-slate-200 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500 sm:text-sm whitespace-pre-wrap"></textarea>
          </div>
          <div class="flex items-center justify-end space-x-4 pt-2">
            <a href={`/posts/${post.id}`} class="px-5 py-2.5 text-sm text-slate-400 hover:text-slate-200 rounded-md transition-colors">取消</a>
            <button type="submit" class="bg-gradient-to-r from-green-500 to-teal-500 hover:from-green-600 hover:to-teal-600 text-white font-semibold py-2.5 px-6 rounded-md shadow-md hover:shadow-lg transform hover:-translate-y-0.5 transition-all duration-150 ease-in-out text-sm">保存更改</button>
          </div>
        </form>
      </div>
    </>
  );
}